
bt.module({builder: function(bt) {

    var j$ = jQuery;

    function addWaypoint(map, i, data, type) {
        var image = new google.maps.MarkerImage(STATIC_URL+'img/places_map_icon.png?v=20120919',
                new google.maps.Size(42, 34),
                new google.maps.Point(0, 0),
                new google.maps.Point(16, 30));

        var marker = new google.maps.Marker({
            position: data[0],
            map: map,
            icon: image
        });
    }

    function getData(point) {
        var items = point.children();
        var lat = parseFloat($(items[0]).text());
        var lon = parseFloat($(items[1]).text());
        var content = $(items[2]).text();
        var wp_id = null;
        if (items.length > 3)
            wp_id = $(items[3]).text();
        return [new google.maps.LatLng(lat, lon), content, wp_id];
    }

    var initialize = function(widget_id, opts) {
        var myOptions = opts || {
            minZoom: 1,
            maxZoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById(widget_id), myOptions);

        var points = j$('#map_data').children();
        var latlngbounds = new google.maps.LatLngBounds();
        var coordinates = [];

        for (var i = 0; i < points.length; i++) {
            var point = j$(points[i]);
            var type = point.attr('class');
            var data = getData(point);
            addWaypoint(map, i, data, type);
            latlngbounds.extend(data[0]);
            coordinates.push(data[0]);
        }

        if(points.length == 1) {
            map.setCenter(coordinates[0]);
        }
        if(points.length == 0) {
            /* display the whole world */
            latlngbounds.extend(new google.maps.LatLng(70, 150));
            latlngbounds.extend(new google.maps.LatLng(-20, -210));
        }
        map.fitBounds(latlngbounds);
        /* if map looks too small, let it fit the world */
        if(map.getZoom() < 1) {
            var latlngbounds = new google.maps.LatLngBounds();
            latlngbounds.extend(new google.maps.LatLng(70, 150));
            latlngbounds.extend(new google.maps.LatLng(-20, -210));
        }

        return map;
    };

    j$(document).ready(function() {
        bt.gmap.initMapScript(function() {
            initialize("map");
        });
    });

    bt.places.initialize = initialize;

}});
